package com.headcaselabs.s3;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.amazon.s3.S3StreamObject;

public class S3Utils {
   
   /**
    * @param InputStream
    * @return The content length
    * @throws NoSuchAlgorithmException
    * 
    * @throws IOException
    */
   @SuppressWarnings("unchecked")
	public static long addMeta(InputStream is, S3StreamObject object) throws Exception {
       BufferedInputStream bis = new BufferedInputStream(is);
       try {
           MessageDigest messageDigest = MessageDigest.getInstance("MD5");
           byte[] buffer = new byte[16384];
           
           int bytesRead = -1;
           long totalBytes = 0;
           while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
               messageDigest.update(buffer, 0, bytesRead);
               totalBytes += bytesRead;
           }
           byte[] digest = messageDigest.digest();
           String md5hdr = toHex(digest);
           if (object == null || object.metadata == null)
        	  throw new Exception("S3StreamingObject or it's metadata is null");
           object.metadata.put("Content-Length", Arrays.asList(new String[] { String.valueOf(totalBytes) }));
           object.metadata.put("content-md5", Arrays.asList(new String[] { md5hdr }));
           
           return totalBytes;
       } finally {
           try {
               bis.close();
           } catch (Exception e) {
               System.err.println("Unable to close input stream of hash candidate: " + e);
           }
       }
   }
   
   /**
    * @param data
    * @return the Hex String
    */
   public static String toHex(byte[] data) {
       StringBuffer sb = new StringBuffer(data.length * 2);
       for (int i = 0; i < data.length; i++) {
           String hex = Integer.toHexString(data[i]);
           if (hex.length() == 1) {
        	  sb.append("0");
           } else if (hex.length() == 8) {
               hex = hex.substring(6);
           }
           sb.append(hex);
       }
       return sb.toString().toLowerCase();
   }
   
   public static long getBytes(BufferedInputStream is) throws IOException {
  	 byte[] buffer = new byte[16384];
     
     int bytesRead = -1;
     long totalBytes = 0;
     while ((bytesRead = is.read(buffer, 0, buffer.length)) != -1) {
         totalBytes += bytesRead;
     }
     return totalBytes;
  	 
   }

}
